package com.erdos.upc.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.erdos.common.service.BaseCRUDService;
import com.erdos.common.web.LoginUtil;
import com.erdos.upc.core.UpcUtil;
import com.erdos.upc.dao.GroupDao;
import com.erdos.upc.dao.UserDao;
import com.erdos.upc.entity.Group;
import com.erdos.upc.entity.SecurityRole;
import com.erdos.upc.entity.User;
import com.erdos.upc.service.SecurityRoleService;
import com.erdos.upc.service.UserService;

public class UserServiceImpl extends BaseCRUDService<User> implements
		UserService {
	private static final Log logger = LogFactory.getLog(UserServiceImpl.class);
	private UserDao userDao;
	
	private SecurityRoleService securityRoleService;

	private GroupDao groupDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public GroupDao getGroupDao() {
		return groupDao;
	}

	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}

	/**
	 * 完成创建用户对象和用户组关联的创建
	 */
	public Long insert(User user) {
		logger.debug("insert user start!");
		Long sid=userDao.insert(user);
		if (user.getGroups() != null && user.getGroups().size() != 0) {
			for (Group g : user.getGroups()) {
				Group group = this.groupDao.findByName(g.getName());
				Map<String, Object> conditions = new HashMap<String, Object>();
				conditions.put("userSid", user.getSid());
				conditions.put("groupSid", group.getSid());
				conditions.put("createdBy", UpcUtil.getUpcUserPin());
				conditions.put("createdDt", new Date());
				conditions.put("version", 1);
				getUserDao().insertUserGroup(conditions);
			}
		}
		//插入工廠安全角色
		for(SecurityRole role:user.getSecurityRoles()){
		 insertSecurityRole(user,role);
		}
		logger.debug("insert user end");
		return sid;
	}

	/**
	 * 更新用户对象和用户组关联记录
	 */
	public void update(User user) {
		logger.debug("update user start!");
		// 调用Dao的update方法更新用户对象本身
		userDao.update(user);
		// 查询当前数据库关联的用户组oldGroups集合对象
		User oldUser = userDao.findByPrimaryKey(user.getSid());
		List<Group> oldGroups = oldUser.getGroups();
		logger.debug("oldGroups size:" + oldGroups.size());
		// 当前传入用户的新关联newGroups集合对象
		List<Group> newGroups = user.getGroups();
		logger.debug("newGroups size:" + newGroups.size());
		// 需要新插入的用户组主键集合
		List<Group> insertGroups = new ArrayList<Group>();
		// 需要删除的用户组主键集合
		List<Group> deleteGroups = new ArrayList<Group>();
		for (Group group : oldGroups) {
			if (!newGroups.contains(group)) {
				deleteGroups.add(group);
			}
		}
		for (Group group : newGroups) {
			if (!oldGroups.contains(group)) {
				insertGroups.add(group);
			}
		}
		logger.debug("insert groups size:" + insertGroups.size());
		for (Group group : insertGroups) {
			Group g = this.groupDao.findByName(group.getName());
			Map<String, Object> conditions = new HashMap<String, Object>();
			conditions.put("userSid", user.getSid());
			conditions.put("groupSid", g.getSid());
			conditions.put("createdBy", UpcUtil.getUpcUserPin());
			conditions.put("createdDt", new Date());
			conditions.put("version", 1);
			getUserDao().insertUserGroup(conditions);
		}
		logger.debug("deleteGroups size:" + deleteGroups.size());
		for (Group group : deleteGroups) {
			getUserDao().deleteUserGroup(user.getSid(), group.getSid());
		}
		
		updateSecurityRoles(user);
	}

	/**
	 * 检查用户组是否唯一
	 */
	public boolean checkPinExist(String sid, String pin) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pin", pin);
		logger.debug("lazy loading test...1");
		User user = null;
		if (StringUtils.isNotEmpty(pin)) {
			user = getUserDao().findUniqueByParams(params);
		}
		if (StringUtils.isEmpty(sid)) {
			return user == null ? false : true;
		} else {
			if (user != null) {
				if (sid.equals(user.getSid().toString())) {
					return false;
				} else {
					return true;
				}
			} else {
				return false;
			}
		}

	}

	/* (non-Javadoc)
	 * @see com.hp.upc.service.UserService#checkEmailExist(java.lang.String, java.lang.String)
	 */
	public boolean checkEmailExist(String sid, String email) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("email", email);
		logger.debug("lazy loading test...1");
		User user = null;
		if (StringUtils.isNotEmpty(email)) {
			user = getUserDao().findUniqueByParams(params);
		}
		if (StringUtils.isEmpty(sid)) {
			return user == null ? false : true;
		} else {
			if (user != null) {
				if (sid.equals(user.getSid().toString())) {
					return false;
				} else {
					return true;
				}
			} else {
				return false;
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.hp.upc.service.UserService#findUserByPin(java.lang.String)
	 */
	public User findUserByPin(String pin) {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("pin", pin);
		return userDao.findUniqueByParams(params);
	}

	/* (non-Javadoc)
	 * @see com.hp.upc.service.UserService#findUserByUserNameUserGP(java.util.Map)
	 */
	public User findUserByUserNameUserGP(Map<String, Object> params) 
	{
		return this.userDao.findUserByUserNameUserGP(params);
	}

	/* (non-Javadoc)
	 * @see com.hp.upc.service.UserService#insertSecurityRole(java.util.Map)
	 */
	public void insertSecurityRole(User user,SecurityRole role) {
				
				//查找用户的sid
				Map<String,Object> params = new HashMap<String,Object>();
				
				params.put("securityRoleSid", role.getSid());
				params.put("userSid", user.getSid());
				params.put("createdBy", LoginUtil.getUpcUserPin());
				params.put("createdDt", new Date());
				params.put("controlType", 1);
				
				userDao.insertSecurityRole(params);
	}

	/* (non-Javadoc)
	 * @see com.hp.upc.service.UserService#deleteSecRoleByUserSidAndsecSid(java.lang.Long, java.lang.Long)
	 */
	public void deleteSecRoleByUserSidAndsecSid(Long userSid, Long securitySid) {
		userDao.deleteSecRoleByUserSidAndsecSid(userSid, securitySid);	
	}
	public void updateSecurityRoles(User user){
		User oldUser = userDao.findByPrimaryKey(user.getSid());
		List<SecurityRole> oldSecurityRoles = securityRoleService.findSecurityRoleFacByUserSid(user.getSid());
		
		List<SecurityRole> newSecurityRoles = user.getSecurityRoles();
		
		// 需要新插入的用户组主键集合
		List<SecurityRole> insertSecurityRoles = new ArrayList<SecurityRole>();
		// 需要删除的用户组主键集合
		List<SecurityRole> deleteSecurityRoles = new ArrayList<SecurityRole>();
		for (SecurityRole role : oldSecurityRoles) {
			if (!newSecurityRoles.contains(role)) {
				deleteSecurityRoles.add(role);
			}
		}
		for (SecurityRole role : newSecurityRoles) {
			if (!oldSecurityRoles.contains(role)) {
				insertSecurityRoles.add(role);
			}
		}
		
		for (SecurityRole role : insertSecurityRoles) {
			insertSecurityRole(user,role);
		}
		logger.debug("deleteGroups size:" + deleteSecurityRoles.size());
		for (SecurityRole role : deleteSecurityRoles) {
			deleteSecRoleByUserSidAndsecSid(user.getSid(),role.getSid());
		}
	}

	/**
	 * @param securityRoleService the securityRoleService to set
	 */
	public void setSecurityRoleService(SecurityRoleService securityRoleService) {
		this.securityRoleService = securityRoleService;
	}
}
